package com.isyscore.os.metadata.kettle.step;

import com.isyscore.os.metadata.enums.KettleDataFlowNodeType;
import com.isyscore.os.metadata.kettle.base.FlowConfig;
import com.isyscore.os.metadata.kettle.base.Step;
import com.isyscore.os.metadata.kettle.vis.EmptyValueDealNode;
import com.isyscore.os.metadata.kettle.vis.JavaExpressionNode;
import com.isyscore.os.metadata.kettle.vis.VisNode;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleStepException;
import org.pentaho.di.core.plugins.PluginInterface;
import org.pentaho.di.core.plugins.PluginRegistry;
import org.pentaho.di.core.plugins.StepPluginType;
import org.pentaho.di.core.row.value.ValueMetaFactory;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
import org.pentaho.di.trans.steps.emptyValueDeal.EmptyValueDealFunction;
import org.pentaho.di.trans.steps.emptyValueDeal.EmptyValueDealMeta;
import org.pentaho.di.trans.steps.janino.JaninoMeta;
import org.pentaho.di.trans.steps.janino.JaninoMetaFunction;

import java.util.List;

public class JavaExpressionStep implements Step {
    @Override
    public StepMeta decode(VisNode step, List<DatabaseMeta> databases, TransMeta transMeta, FlowConfig transGraph) throws Exception {
        JavaExpressionNode javaExpressionNode =(JavaExpressionNode)step;
        PluginRegistry registry = PluginRegistry.getInstance();
        PluginInterface sp = registry.findPluginWithId( StepPluginType.class, KettleDataFlowNodeType.JavaExpression.name());
        StepMetaInterface stepMetaInterface = (StepMetaInterface) registry.loadClass( sp );

        JaninoMeta janinoMeta = (JaninoMeta) stepMetaInterface;
        //参数封装
        JaninoMetaFunction[] jfs  =new JaninoMetaFunction[javaExpressionNode.getExpressions().size()];
        for (int i = 0; i < javaExpressionNode.getExpressions().size(); i++) {
            JavaExpressionNode.Expression expression = javaExpressionNode.getExpressions().get(i);
            JaninoMetaFunction jf = new JaninoMetaFunction(expression.getField(),expression.getExpression(),ValueMetaFactory.getIdForValueMeta(expression.getType()!=null?expression.getType().name():null),-1,-1,null);
            jfs[i] = jf;
        }

        janinoMeta.setFormula(jfs);
        janinoMeta.setErrorDealType(javaExpressionNode.getErrorDealType());

        StepMeta stepMeta = new StepMeta(KettleDataFlowNodeType.JavaExpression.name(), javaExpressionNode.getNodeName(), stepMetaInterface);
        stepMeta.setDraw(true);
        return stepMeta;
    }

    public StepMeta after(VisNode step, List<DatabaseMeta> databases, TransMeta transMeta, FlowConfig transGraph) throws KettleStepException {
        return null;
    }

}
